package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.PhotoGridAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.common.ZoomImagePoup;
import com.dchh.android.suverynew.presenter.ITzpPhotoPresenter;
import com.dchh.android.suverynew.presenter.impl.TzpPhotpPresenter;
import com.dchh.android.suverynew.view.ITzpPhotoView;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.ImageInfoBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.InputPopupWindow;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.PhotoUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图纸拍摄
 *
 * @author zhoudan
 * @date 2016年2月23日
 */
public class TZPhotoActivity extends SBaseActivity implements ITzpPhotoView {
    private TextView title;
    private GridView gridView;
    private LinearLayout camera;
    private ToggleButton btn;

    private List<ImageInfoBean> imageInfoList = new ArrayList<ImageInfoBean>();
    private PhotoGridAdapter adapter;

    /**
     * 任务包存储路径
     */
    private String root;
    private String taskName;
    private String dbPath;

    private String tableName = "PHOTO";
//    private String beizhu1 = "1作物";
//    private String beizhu2 = "2图纸";

    private boolean tzExist = false; //图纸是否已经拍摄过照片

    private DBManagerUtil dbManagerUtil;
    private PhotoUtil photoUtil;

//    private int type; //1--作物  2-- 图纸

    /**
     * 1--任务包  2--村  3--样方
     */
    private int type; //1--任务包  2--村  3--样方

    private boolean click = true;
    private String YFBHU;
    private String MYBZ;

    private String CUNDM;
    private String CUNMING;
    private String dcqb;

    private String period;
    private String titleTxt;
    private List<String> keys = new ArrayList<String>();
    private List<Map<String, String>> datas;

    //-------------------拍照-------------------------
    private final static int CAMERA_RESULT = 800;

    private ITzpPhotoPresenter mTzpPhotoPresenter = new TzpPhotpPresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_zw_grid);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {
        toolbar_title.setText(titleTxt);
    }

    @Override
    public void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        taskName = getIntent().getStringExtra("taskName");
        dbPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";

        period = getIntent().getStringExtra("period");
        period = period.contains("早稻面积") ? "春播面积" : period;
        dcqb = period + "-" + "遥感面积调查表";
        dbManagerUtil = DBManagerUtil.getInstance(dbPath, this);
        type = getIntent().getIntExtra("type", 1);
        titleTxt = "图纸拍摄";
        if (type == 1) {
            titleTxt = taskName + titleTxt;
        } else if (type == 2) {
            CUNMING = Constants.tzps_parent.get(Constants.tzps_node.getItem().getFeild());
            CUNDM = Constants.tzps_parent.get("CUNDM");
            titleTxt = CUNMING + titleTxt;
        } else {
            CUNMING = Constants.tzps_parent.get(Constants.tzps_node.getItem().getFeild());
            CUNDM = Constants.tzps_parent.get("CUNDM");
            YFBHU = Constants.select.get("YFBHU");
            MYBZ = Constants.select.get("备注");
            titleTxt = CUNMING + "样方" + Constants.select.get("YFBH") + titleTxt;
        }
        initPhoto();
        mTzpPhotoPresenter.getInitDatas(type, taskName, CUNMING, dcqb, YFBHU, tableName, dbPath, dbManagerUtil, photoUtil);
        title = (TextView) findViewById(R.id.title_textview);
        gridView = (GridView) findViewById(R.id.photo_grid);
        camera = (LinearLayout) findViewById(R.id.opreate_layout);
        btn = (ToggleButton) findViewById(R.id.edit_btn);

        String subtitle = "图纸照片";
        gridView.setNumColumns(1);

        title.setText(subtitle);

        camera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });

        btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter.setDeleteFlag(isChecked);
                adapter.notifyDataSetChanged();
            }
        });

        if (adapter == null) {
            adapter = new PhotoGridAdapter(this, imageInfoList);
            adapter.setImageOperate(imgOp);
            gridView.setAdapter(adapter);
        }

        btnEnable();

        setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageInfoList.size() > 0) {
                    finish();
                } else {
                    isAlertDialog(TZPhotoActivity.this, "图纸照片没有拍摄，是否退出？", "退出", "继续拍照");
                }
            }
        });
    }

    private void btnEnable() {
        btn.setChecked(false);
        if (imageInfoList.size() > 0) {
            btn.setEnabled(true);
        } else {
            btn.setEnabled(false);
        }
    }

    PhotoGridAdapter.ImageOperate imgOp = new PhotoGridAdapter.ImageOperate() {

        @Override
        public void OnShow(int position, View view) {
            String path = imageInfoList.get(position).getAbsolutePath();
            if (StringUtil.isNotEmpty(path)) {
                File file = new File(path);
                if (file.exists()) {
                    ZoomImagePoup zp = new ZoomImagePoup(TZPhotoActivity.this);
                    zp.show(view, path, photoUtil);
                } else {
                    CommenUtil.toast("图片不存在!", TZPhotoActivity.this);
                }
            } else {
                CommenUtil.toast("图片路径为空!", TZPhotoActivity.this);
            }
        }

        @Override
        public void OnDelete(int position) {
            String rowid = datas.get(position).get("rowid");
            String path = imageInfoList.get(position).getAbsolutePath();

            boolean flag = dbManagerUtil.deleteById(tableName, "rowid", rowid, dbPath);
            if (flag) {
                photoUtil.deleteAttachmentFile(path);
                datas.remove(position);
                imageInfoList.remove(position);
                adapter.notifyDataSetChanged();

                btnEnable();

                tzExist = false;
                adapter.clearMemory();

                Constants.data_refresh = true;
            } else {
                CommenUtil.toast("删除失败", TZPhotoActivity.this);
            }
        }

    };


    private void initPhoto() {
        String photopath = root + "/" + taskName + "/SYSTEM/images/tuzhi/" + dcqb;
        if (type == 1) {
//            photopath += taskName;
        } else if (type == 2) {
            photopath += "/" + CUNMING;
        } else {
            photopath += "/" + CUNMING + "/" + YFBHU;
        }


        photoUtil = new PhotoUtil(this);
        photoUtil.setFilePath(photopath);
    }

    private void takePhoto() {
        String photoName = "";
        photoName = FileUtil.getPhotoFileName(".jpg");
        String path = photoUtil.getSavePath(photoName);
        photoUtil.takePhoto(path);
    }

    /**
     * 拍照返回结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_RESULT) {
            if (photoUtil.getPhotoSize(photoUtil.mPhotoPath) == 0) {// 文件内容为空
                photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
            } else {
                String imageName = "抽样调查图纸";
                if (type == 1) {
                    imageName = taskName + "抽样调查图纸";
                    savePhoto(imageName, "");
                } else if (type == 2) {
                    imageName = CUNMING + "抽样调查图纸";
                    savePhoto(imageName, "");
                } else {
                    doWithCydc();
                }

            }
        }
    }

    /**
     * 处理后期图片
     *
     * @param bitmap
     */
    String myBz = null;

    private void doWithCydc() {
        InputPopupWindow poup = new InputPopupWindow(this);
        poup.showInputPoupWindow(findViewById(R.id.contentArea), null, "样方位置描述", true, 0, false);
        poup.setClicklistener(new InputPopupWindow.ClickListenerInterface() {

            @Override
            public void doConfirm(String value) {
                if (click) {
                    click = false;
                    myBz = value;
                    String imageName = YFBHU + "抽样调查图纸";
                    savePhoto(imageName, value);
                } else {
                    CommenUtil.toast("正在处理，请稍后...", TZPhotoActivity.this);
                }
            }

            @Override
            public void doCancel() {
                if (click) {
                    click = false;
                    photoUtil.releaseImage(photoUtil.mPhotoPath);
                    photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
                    click = true;
                } else {
                    CommenUtil.toast("正在处理，请稍后...", TZPhotoActivity.this);
                }
            }

        });

    }

    /**
     * 保存照片
     */
    private void savePhoto(String imageName, String beizhu) {
        Dialog dialog = MyLoadingDialog.createLoadingDialog(TZPhotoActivity.this, "正在处理照片，请稍后...");
        dialog.show();

        String date = photoUtil.getCurrTime("yyyy-MM-dd");
        String location = CommenUtil.getLatLon();// 获取当前地址经纬度
        String lat = "", lon = "";
        if (StringUtil.isNotEmpty(location)) {
            lat = location.split(",")[0];
            lon = location.split(",")[1];
        }
        //处理图片旋转
        int degree = photoUtil.getRotate(photoUtil.mPhotoPath);
        if (degree != 0) {
            photoUtil.rotateBitmap(photoUtil.mPhotoPath, degree);
        }
        //处理水印
        String mark = imageName + ",日期：" + date;
        if (type == 1) {
            mark += "," + "任务包：" + taskName;
        } else if (type == 2) {
            mark += "," + "村名称：" + CUNMING;
        } else {
            mark += "," + "样方编号：" + YFBHU + ",备注：" + beizhu;
        }

        Bitmap bitmap = photoUtil.doPhoto(photoUtil.mPhotoPath, mark);
        if (bitmap != null) {
            if (tzExist) {
                String rowid = datas.get(0).get("rowid");
                dbManagerUtil.deleteById(tableName, "rowid", rowid, dbPath);
            }
            photoUtil.renameFile(photoUtil.mPhotoPath, imageName);
            saveToDB(imageName, lon, lat, date);
            mTzpPhotoPresenter.getInitDatas(type, taskName, CUNMING, dcqb, YFBHU, tableName, dbPath, dbManagerUtil, photoUtil);
            adapter.clearMemory();
            adapter.notifyDataSetChanged();

            btnEnable();
            System.out.println("拍照成功--保存到数据库");
        } else {
            photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
        }

        click = true;
        dialog.dismiss();
    }


    /**
     * 保存到数据库
     */
    public void saveToDB(String value, String lon, String lat, String date) {
//        String beizhu = beizhu2;

        String pid = "_" + photoUtil.getCurrTime(null);
        String pkg = "", cun = "", yfbh = "";

        String uuid = "", puuid = "", level = "";

        if (type > 0) {
            pid = taskName + pid;
            pkg = taskName;

            uuid = Constants.currentTask.getTaskid();
            puuid = "";
            level = "000";
            if (type > 1) {
                pid = CUNMING + pid;
                cun = CUNMING;

                uuid = CUNDM;
                puuid = Constants.currentTask.getTaskid();
                level = "001";
                if (type > 2) {
                    pid = YFBHU + pid;
                    yfbh = YFBHU;

                    uuid = YFBHU;
                    puuid = CUNDM;
                    level = "002";
                }
            }
        }
        String beizhu = myBz;
        Map<String, String> map = new HashMap<String, String>();
        map.put("PHOTOID", pid);
        map.put("FILENAME", value + ".jpg");
        map.put("LON", lon);
        map.put("LAT", lat);
        map.put("DATE", date);

        map.put("村级行政区名称", cun);
        map.put("样方编号", yfbh);

        map.put("自然地块编号", "");
        map.put("主要地物", "");
        map.put("备注", beizhu);
        map.put("DCQB", dcqb);
        map.put("TYPE", String.valueOf(type));
        map.put("COUNTY", pkg);

        dbManagerUtil.add(map, keys, tableName, "", dbPath);

        Constants.data_refresh = true;

        //保存进度记录
        RecordDBManager rcdDB = new RecordDBManager(TZPhotoActivity.this);
        rcdDB.add(uuid, puuid, "2", level);

    }

    //-------------------拍照【完】--------------------


    private void isAlertDialog(final Activity activity, String str, String right, String left) {
        final AlertDialog alertDialog = new AlertDialog(activity, str, right, left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();
                TZPhotoActivity.this.finish();
                TZPhotoActivity.this.overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void onInitData(List<Map<String, String>> datas, List<ImageInfoBean> imageInfoList) {
        this.datas = datas;
        this.imageInfoList = imageInfoList;
        if (datas != null && datas.size() > 0) {
            tzExist = true;
        } else {
            tzExist = false;
        }
    }
}
